from django.shortcuts import render
from django.http import HttpResponse
import json
from .utils import api, query, current_datetime
from sportmeeting.models import *


# Create your views here.

def login(request):
    """
    登录 POST: /login

    :param request:
    :return:
    """
    if request.method == 'POST':
        try:
            json_data = json.loads(request.body)
            username = json_data['username']
            password = json_data['password']
        except:
            return api({'msg': 'json格式不正确'}).error()
        arglist = ['username', 'password', 'id', 'name', 'gender']  # 返回数据的参数名
        res = query(Player).get(arglist, username=username, password=password)
        if res:
            return api(res[0]).success()
        else:
            return api({'msg': "账号不存在或密码错误"}).error()

    return api('must be post').error()


def register(request):
    """
    注册 POST: /register

    :param request:
    :return:
    """
    if request.method == 'POST':
        try:
            json_data = json.loads(request.body)
            username = json_data['username']
            password = json_data['password']
            name = json_data['name']
            gender = json_data['gender']
            institutionid = json_data['institutionid']
        except:
            return api({'msg': 'json格式不正确'}).error()

        if Player.objects.filter(username=username).exists():
            return api('账号已存在').error()
        else:
            try:
                Player.objects.create(
                    username=username,
                    password=password,
                    name=name,
                    gender=gender,
                    institution_id=institutionid
                )
                return api('注册成功').success()
            except Exception as e:
                return api(e).error()
    else:
        return api([]).error()


def institutions(request):
    """
    获取学院列表 GET: /institutions

    :param request:
    :return:
    """
    if request.method == 'GET':
        ins_id = request.GET.get('id', '')
        argslist = ['id', 'name']  # 返回数据的参数名
        if ins_id == '':
            return api(query(Institution).all(argslist)).success()
        else:
            return api(query(Institution).filter(argslist, id=ins_id)).success()


def games(request):
    """
    获取比赛 GET: /games

    :param request:
    :return:
    """
    if request.method == 'GET':
        game_id = request.GET.get('id', '')
        arglist = ['id', 'name', 'game_type', 'type', 'gender', 'unit', 'data', 'status', 'start_time',
                   'end_time']  # 返回数据的参数名
        if game_id == '':
            return api(query(Game).all(arglist)).success()
        else:
            return api(query(Game).filter(arglist, id=game_id)).success()


def enroll_model(request):
    """
    获取报名表 GET: /enroll
    提交报名表 POST: /enroll

    :param request:
    :return:
    """
    if request.method == 'GET':
        enroll_id = request.GET.get('id', '')
        if enroll_id == '':
            items = enroll.objects.all()
            datalist = []
            for item in items:
                datalist.append(
                    {'id': item.id,
                     'name': item.player.name,
                     'institution': item.player.institution.name,
                     'gameid': item.game.id,
                     'game_name': item.game.name,
                     # 'finall_gameid': item.finall_game.id,
                     # 'finall_game': item.finall_game.name,
                     'gender': item.game.gender,

                     }
                )
            return api(datalist).success()
        else:
            ins = enroll.objects.filter(id=enroll_id)
            datalist = []
            for item in ins:
                datalist.append(
                    {'id': item.id,
                     'name': item.player.name,
                     'institution': item.player.institution.name,
                     'game_name': item.game.name,
                     'gender': item.game.gender,
                     'gameid': item.game.id,
                     }
                )
            return api(datalist).success()
    else:
        try:
            json_data = json.loads(request.body)
            username = json_data['username']
            password = json_data['password']
            gameId = json_data['gameId']
            player = Player.objects.get(username=username, password=password)
            game = Game.objects.get(id=gameId)
            if enroll.objects.filter(player=player, game=game):
                return api({'msg': '请勿重复报名！'}).error()

            enroll.objects.create(
                player=player,
                game=game,
                finall_game=Game.objects.get(id=3),
            )
            return api({'msg': '报名成功'}).success()
        except:
            return api({'msg': 'json格式不正确'}).error()


def complain(request):
    """
    提交投诉 POST: /complain

    :param request:
    :return:
    """
    if request.method == 'POST':
        try:
            json_data = json.loads(request.body)
            contact = json_data['contact']
            content = json_data['content']
        except:
            return api({'msg': 'json格式不正确'}).error()
        try:
            Complaint.objects.create(
                contact=contact,
                content=content
            )
            return api({'msg': '投诉提交成功'}).success()
        except:
            return api({'msg': '投诉提交错误'}).error()
    else:
        return api({'msg': '投诉提交错误'}).error()


def news(request):
    """
    查询新闻 GET: /news

    :param request:
    :return:
    """
    if request.method == 'POST':
        try:
            json_data = json.loads(request.body)
            title = json_data['title']
            content = json_data['content']
        except:
            return api({'msg': 'json格式不正确'}).error()
        try:
            News.objects.create(
                title=title,
                content=content,
            )
            return api({'msg': '提交成功'}).success()
        except:
            return api({'msg': '投诉错误'}).error()
    else:
        argslist = ['id', 'title', 'content', 'create_time']  # 返回数据的参数名

        news_id = request.GET.get('id', '')
        if news_id == '':
            return api(query(News).all(argslist)).success()
        else:
            return api(query(News).filter(argslist, id=news_id)).success()


def player(request):
    """
    获取运动员赛事 GET: /player

    :param request:
    :return:
    """
    if request.method == 'GET':
        username = request.GET.get('username')
        try:
            playerobj = Player.objects.get(username=username)
        except:
            return api("查无此用户").error()

        items = playerobj.enroll_set.all()
        data = []
        for item in items:
            data.append(
                {
                    "gameid": item.game.id,
                    "game": str(item.game),
                    "finall_gameid": item.finall_game.id,
                    "finall_game": str(item.finall_game),
                    "uid": item.player.id,
                    "name": item.player.name,
                    "institution": item.player.institution.name

                }
            )
        return api(data).success()


def cancle(request):
    """
    取消报名 POST: /cancle

    :param request:
    :return:
    """
    if request.method == 'POST':
        try:
            json_data = json.loads(request.body)
            username = json_data['username']
            password = json_data['password']
            gameid = json_data['gameid']
            game = Game.objects.get(id=gameid)
            try:
                user = Player.objects.get(username=username, password=password)
            except:
                return api({'msg': '账号密码错误'}).error()
            game = enroll.objects.get(player=user, game=game)
            game.delete()
            return api({'msg': '取消成功', 'gameid': gameid}).success()
        except:
            return api({'msg': '非法操作'}).error()
    else:
        return api({'msg': 'the method must be post'}).error()
